<template>
  <div class="music-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>音乐管理</span>
          <el-button type="primary" @click="dialogVisible = true">上传音乐</el-button>
        </div>
      </template>
      
      <!-- 音乐文件列表 -->
      <el-table :data="musicList" v-loading="loading" stripe>
        <el-table-column prop="filename" label="文件名"/>
        <el-table-column prop="file_size" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="playlist_name" label="二级分类" width="150" />
        <el-table-column prop="created_at" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="playMusic(row)">播放</el-button>
            <el-button size="small" type="danger" @click="handleDeleteMusic(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 音乐上传对话框 -->
    <el-dialog 
      title="上传音乐" 
      v-model="dialogVisible" 
      width="600px"
      @close="resetUploadForm"
    >
      <el-form 
        ref="uploadFormRef" 
        :model="uploadForm" 
        :rules="uploadRules" 
        label-width="140px"
      >
        <el-form-item label="音乐文件" prop="file">
          <el-upload
            ref="uploadRef"
            class="music-uploader"
            drag
            :auto-upload="false"
            :show-file-list="true"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept="audio/*"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传音频文件，且不超过100MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择分类">
            <el-option label="身心放松" value="身心放松" />
          </el-select>
        </el-form-item>

   
        
        <el-form-item label="二级分类" prop="playlist_name">
           <el-select v-model="uploadForm.playlist_name" placeholder="请选择分类">
            <el-option label="身心放松音乐" value="身心放松音乐" />
            <el-option label="脑波放松音乐" value="脑波放松音乐" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadMusic" :loading="uploading">上传</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 音乐播放对话框 -->
    <el-dialog 
      title="音乐播放" 
      v-model="playerVisible" 
      width="500px"
      @close="stopMusic"
    >
      <div class="music-player">
        <h3>{{ currentMusic?.filename }}</h3>
        <audio 
          ref="audioPlayer" 
          :src="currentMusic?.oss_url" 
          controls 
          style="width: 100%; margin-top: 20px;"
          @play="onPlay"
          @pause="onPause"
          @ended="onEnded"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/format'
import { musicApi } from '../../api/music'

interface MusicFile {
  id: number
  filename: string
  oss_key: string
  oss_url: string
  file_size: number
  duration: number
  category: string
  playlist_name: string
  uploader_id: number
  created_at: string
}

const loading = ref(false)
const uploading = ref(false)
const musicList = ref<MusicFile[]>([])
const dialogVisible = ref(false)
const playerVisible = ref(false)
const currentMusic = ref<MusicFile | null>(null)
const audioPlayer = ref<HTMLAudioElement | null>(null)

const uploadFormRef = ref<FormInstance>()
const uploadRef = ref()

const uploadForm = reactive({
  file: null as File | null,
  category: '',
  playlist_name: ''
})

const uploadRules = {
  file: [
    { required: true, message: '请上传音乐文件', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取音乐文件列表
const loadMusicList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response: any = await musicApi.getMusicFiles(params)
    musicList.value = response.files
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取音乐文件列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleFileChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    uploadForm.file = uploadFile.raw
  }
}

const handleFileRemove = () => {
  uploadForm.file = null
}

const uploadMusic = async () => {
  if (!uploadFormRef.value || !uploadForm.file) return
  
  await uploadFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      uploading.value = true
      
      // 创建FormData对象来发送文件和附加数据
      const formData = new FormData()
      formData.append('file', uploadForm.file!)
      formData.append('category', uploadForm.category)
      formData.append('playlist_name', uploadForm.playlist_name)
      
      // 上传音乐文件
      await musicApi.uploadMusicFileWithFormData(formData)
      
      ElMessage.success('音乐文件上传成功')
      
      dialogVisible.value = false
      loadMusicList()
    } catch (error) {
      ElMessage.error('音乐文件上传失败')
      console.error(error)
    } finally {
      uploading.value = false
    }
  })
}

const resetUploadForm = () => {
  uploadForm.file = null
  uploadForm.category = ''
  uploadForm.playlist_name = ''
  
  if (uploadFormRef.value) {
    uploadFormRef.value.resetFields()
  }
  
  // 清除上传组件的文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const playMusic = (music: MusicFile) => {
  currentMusic.value = music
  playerVisible.value = true
  
  // 等待DOM更新后自动播放
  setTimeout(() => {
    if (audioPlayer.value) {
      audioPlayer.value.play().catch(error => {
        console.log('自动播放失败:', error)
      })
    }
  }, 100)
}

const stopMusic = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause()
    audioPlayer.value.currentTime = 0
  }
  currentMusic.value = null
}

const onPlay = () => {
  console.log('音乐开始播放')
}

const onPause = () => {
  console.log('音乐暂停播放')
}

const onEnded = () => {
  console.log('音乐播放结束')
  playerVisible.value = false
}

const handleDeleteMusic = async (music: MusicFile) => {
  ElMessageBox.confirm('确定要删除该音乐文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用删除音乐文件的API
      await musicApi.deleteMusicFile(music.id)
      ElMessage.success('音乐文件删除成功')
      loadMusicList()
    } catch (error) {
      ElMessage.error('音乐文件删除失败')
      console.error(error)
    }
  })
}

const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let fileSize = size
  
  while (fileSize >= 1024 && unitIndex < units.length - 1) {
    fileSize /= 1024
    unitIndex++
  }
  
  return `${fileSize.toFixed(2)} ${units[unitIndex]}`
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadMusicList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadMusicList()
}

onMounted(() => {
  loadMusicList()
})
</script>

<style scoped lang="scss">
.music-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .music-uploader {
    width: 100%;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .music-player {
    text-align: center;
  }
}
</style>